<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  .weui-cells__title {
    text-align: left;
  }
  .oitem {
    padding: 3px;
  }
  .hide {
    display: none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_files {
    list-style: none;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
    background: #fff;
  }
  .examine >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .examine >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .weui-cell_select {
    padding: 0 15px;
  }
</style>
<template>
  <div class="examine">
    <div class="rj-wrap">
      大订单派单
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input class="weui-input" type="hidden" name="entity.parentguid" :value="id">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单编号</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="baseInfo.sellcode" name="">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">申请人：</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text" :value="baseInfo.applyname" >
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所在部门</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="" :value="baseInfo.depname">
            </div>
          </div>
          <div class="weui-cell weui-cell_select" style="padding: 0 15px;">
            <div class="weui-cell__hd"><label for="" class="weui-label">客户</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" ref="customername" name="entity.customername" />
              <select class="weui-select" name="entity.customerguid" id="customer" v-model="customerid">
                <option value="" style="color: #ccc;">请选择客户</option>
                <option  v-for="(item, i) in customers" :value="item.guid" >{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell weui-cell_select" v-if="addresses.length > 0" style="padding: 0 15px;">
            <div class="weui-cell__hd"><label for="" class="weui-label">收货地址</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="addressid">
                <option value="" style="color: #ccc;">请选择地址</option>
                <option  v-for="(addr, i) in addresses" :value="addr.guid" >{{addr.province}}{{addr.city}}{{addr.district}}  {{addr.addres}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell" v-if="orderfiles.length > 0">
            <div class="weui-cell__hd"><label class="weui-label">附件</label></div>
            <div class="weui-cell__bd">
              <a v-for="(item, index) in orderfiles" :href="item.url">
                <input class="weui-input" type="text" name="" :value="item.filename">
              </a>
              <!--              <input class="weui-input" type="text" name="" :value="baseInfo.createtime">-->
            </div>
          </div>

        </div>
        <DispatchCustomItem v-for="(item, index) in oitems" :key="index" :itemNo="item" :isLast="index+1 == oitems.length" :sellformid="id" :settletype="baseInfo.settletype" :contract="contracts.length != 0 ? contracts[0] : ''" :quitsrtype="baseInfo.quitsrtype" :benifitordeduct="benifitordeduct" :benefittype="benefittype" :discount="discount" :currency="baseInfo.currency" :items="baseInfo.items"  @doAddItem="addItem(index + 1)" @doDelItem="delItem"></DispatchCustomItem>
        <div ref="actHtml" class="fixcont">
          <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary halfbtn subbtn" href="javascript:" @click="postForm">提交</a>
            <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
          </div>
        </div>
      </form>
    </div>
    <div id="bmlogs">
      <SalesOperationLogs2 :nodeid="nodeid" :orderid="id" :srguid="baseInfo.storermguid" :departid="baseInfo.depguid"></SalesOperationLogs2>
    </div>
  </div>
</template>

<script>
  import DispatchCustomItem from "./DispatchCustomItem";
  import SalesOperationLogs2 from '../common/SalesOperationLogs2'

  export default {
    name: 'DispatchCustomer',
    data () {
      return {
        openid: localStorage.openid,
        id: '',
        baseInfo: {},
        customers: [],
        customerid: '',
        oitems: [0],
        nodeid: '',
        annex: '',
        settledWeight: 0,
        settledCount: 0,
        addresses: [],
        contracts: [],
        benifitordeduct: '',
        benefittype: '',
        discount: '',
        orderfiles: []
      }
    },
    components: {DispatchCustomItem, SalesOperationLogs2},
    mounted () {
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight);

      this.id = this.$route.query.guid;
      this.nodeid = this.$route.query.nodeid;
      this.annex = this.$route.query.annex;
      //this.type = this.$route.query.type;
      this.getBaseInfo();
      this.getCustomers();
      this.getSettledWeight();
      this.getSettledCount();
      this.getFiles();
    },
    watch: {
      'customerid': function (val) {
        this.$nextTick(function () {
          let customername = $('#customer').find('option:selected').text() == '' ? this.baseInfo.customername : $('#customer').find('option:selected').text();
          this.$refs.customername.value = customername;
        })
        this.getAddress();

        this.getContract();
        this.getDiscountType();
      }
    },
    methods: {
      getFiles: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Fileinfo!getFileinfo.action',
          params: {orderid: this.id}
        }).then(response => {

          if (response.data.msg == 'success') {
            this.orderfiles = response.data.files;
          } else {
            //失败时不提示
          }
        });
      },
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function() {
        this.oitems.pop();
      },
      getBaseInfo: function() {
        this.axios({
          method: 'post',
          url: '/sales/Sellform!getBaseinfo.action',
          params:  {sellformid: this.id}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.baseInfo = response.data.weight;
            this.customerid = this.baseInfo.customerguid;


          } else {
            this.toastText('获取大订单信息失败')
          }
        });
      },
      getAddress: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Addresrecord!findAddress.action?operatorid=' + this.customerid
        }).then(response => {
          if (response.data.status == "true") {
            that.addresses = response.data.result;
          } else if (response.data.status == "false") {
            this.toastText(response.data.result);
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误');
        }
        });
      },

      getCustomers: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Customer!getCustomers.action',
          params: {departid: this.baseInfo.depguid, functiontype: 13}
        }).then(response => {
          if (response.data.msg == "success") {
            that.customers = response.data.customers;
          } else {
            this.toastText('获取客户数据失败');
          }
        });
      },
      getSettledWeight: function() {
        this.axios({
          method: 'post',
          url: '/sales/Sellform!getChildsWeight.action',
          params:  {sellformid: this.id}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.settledWeight = response.data.weight != undefined ? response.data.weight : 0;
          } else {
            this.toastText('获取大订单已派单重量失败')
          }
        });
      },
      getSettledCount: function() {
        this.axios({
          method: 'post',
          url: '/sales/Sellform!getChildsCounts.action',
          params:  {sellformid: this.id}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.settledCount = response.data.counts != undefined ? response.data.counts : 0;
          } else {
            this.toastText('获取大订单已派单件数失败')
          }
        });
      },
      getDiscountType: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!getDiscountType.action',
          params: {type: this.baseInfo.quitSRType}
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.benifitordeduct = data.msg.benifitordeduct;
            this.benefittype = data.msg.benefittype;
            this.discount = data.msg.discount;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取赠送数据失败');
          }
        });
      },
      getContract: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Salecontract!getContract.action',
          params: {customerid: this.customerid, status: 1}
          // params: {customerid: '120ED2C35C7D462ABE3F9E095B1E0F4F', orgguid: '0A9BB9B7213C4ECAA6B2C9C2ADD5AF13', status: 1}
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.contracts = data.msg;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取销售合同数据失败');
          }
        });
      },

      postForm: function () {
        let that = this;
        if (this.customerid == '') {
          this.toastText('请选择客户！');
          return false;
        } else if (!this.checkEmy('product')) {
          this.toastText('产品有误！');
          return false;
        } else if (!this.checkEmy('specif')) {
          this.toastText('规格有误！');
          return false;
        } else if (!this.checkEmy('weight')) {
          this.toastText('重量有误！');
          return false;
        } else {
          if (this.baseInfo.settletype == 2) {
            let inputedWei = 0;
            for (let i=0; i<$('.weight').length; i++) {
              inputedWei += parseFloat($('.weight').eq(i).val());
            }

            if (inputedWei + parseFloat(this.settledWeight) > this.baseInfo.orderweight) {
              this.toastText('输入的重量和超出未派单大订单重量！');
              return false;
            }
          } else if (this.baseInfo.settletype == 1) {
            let inputedCount = 0;
            for (let i=0; i<$('.count').length; i++) {
              inputedCount += parseInt($('.count').eq(i).val());
            }

            if (inputedCount + parseInt(this.settledCount) > this.baseInfo.orderpack) {
              this.toastText('输入的件数和超出未派单大订单件数！');
              return false;
            }
          }

        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData.nodeid = this.nodeid;
        this.axios({
          method: 'post',
          url: '/sales/Sellform!dispatch.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            this.toastSuccess('提交成功!');
            this.$router.push({name: 'Sellform'});
          } else if (response.data.msg == 'canotopt'){
            this.toastText('不允许的操作!');
          } else if (response.data.msg == 'outlogin') {
            this.toastText('请重新登录');
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误');
        }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      openLogs: function() {
        this.$router.push({name: 'SalesOperationLogs2', query: {orderid: this.id, srguid: this.baseInfo.storermguid, departid: this.baseInfo.depguid}});
      }
    }
  }
</script>
